package ru.ifmo.croak.impl.replication.team1.sync;

import org.slf4j.LoggerFactory;
import ru.ifmo.croak.impl.replication.team1.LocalContext;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SynchronizerClient implements Runnable {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(SynchronizerWorker.class);
    private static final int SO_TIMEOUT = 10000;
    private final InetSocketAddress socketAddress;
    private final LocalContext localContext;

    public SynchronizerClient(InetSocketAddress socketAddress, LocalContext localContext) {
        this.socketAddress = socketAddress;
        this.localContext = localContext;
    }

    public void run() {
        try {
            log.debug("connect to {}", socketAddress);
            Socket socket = new Socket();
            socket.setSoTimeout(SO_TIMEOUT);
            socket.connect(socketAddress);
            log.debug("connected to {}", socketAddress);
            new SynchronizerWorker(socket, true, localContext).run();
        } catch (IOException e) {
            log.warn("Unexpected IOException, maybe network goes down?", e);
        }
    }
}
